<template>
	<coreshop-page bgColor="rgba(0,0,0,0)" :isShowStatusBarHeight="false" :placeholder="false" showLoginModalDom
		needLoadingPage :loadingPage="loadingPage">
		<view class="goods-detail">
			<!-- 商品详情 -->
			<GoodsDetail :goodsId="state.goodsDetailData?.id" :goodsDetailData="state.goodsDetailData"
				:swiperBanner="state.swiperBanner" :spesDesc="state.spesDesc"
				:goodsDetailContent="state.goodsDetailContent" :isActivityGoods="true" :shareType="ShareEnum.seckill"
				@hanldeShowGoodSku="hanldeShowGoodSku">
				<template #tip>
					<view class="tip-box" v-if="state.showTip && state.goodsDetailData.groupPromotionResult">
						<view class="title">当前秒杀活动规则：</view>
						<view class="desc">{{ state.goodsDetailData.groupPromotionResult }}</view>
						<view class="icon-close" @click="state.showTip = !state.showTip">
							<uv-icon name="close" color="#fff" size="15"></uv-icon>
						</view>
					</view>
				</template>
				<template #countDown>
					<view class="time-box">
						<view class="title">仅剩：</view>
						<uv-count-down :time="state.goodsDetailData.groupTimestamp * 1000" format="DD天HH时mm分ss秒"
							autoStart millisecond @change="onChange">
							<view class="time">
								<text class="time_item">
									{{ state?.timeData?.days }}
								</text>天
								<text class="time_item">
									{{ state?.timeData?.hours > 10 ? state?.timeData?.hours : '0' +
                                        state?.timeData?.hours }}
								</text>时
								<text class="time_item">
									{{ state?.timeData?.minutes }}
								</text>分
								<text class="time_item">
									{{ state?.timeData?.seconds }}
								</text>秒
							</view>
						</uv-count-down>
					</view>
				</template>
			</GoodsDetail>

			<!-- 为您推荐 -->
			<GoodsDetailRecommend></GoodsDetailRecommend>

			<!-- 底部 购买 -->
			<GoodsDetailBottomTabbar>
				<template #bottomTabbar>
					<view class="btn-box" @click="hanldeShowGoodSku">
						立即秒杀
					</view>
				</template>
			</GoodsDetailBottomTabbar>

			<!-- 商品sku弹框 -->
			<GoodsDetailSkuPopup :showSku="state.showSku" :goodsDetailData="state.goodsDetailData"
				:isShowAddCartBtn="false" btnBuyTitlt="立即秒杀" :buyNowNowloading="loading"
				@handleChangePopup="handleChangePopup" @handleBuyNow="handleSeckillNow"></GoodsDetailSkuPopup>
		</view>
	</coreshop-page>
</template>
<script setup lang="ts">
	import { reactive, ref } from 'vue';
	import { onLoad, onShareAppMessage, onShareTimeline, onPullDownRefresh } from '@dcloudio/uni-app';
	import { queryActivityDetial, queryCartNum, queryAddCart } from '@/core/api';
	import { PaymentTypeEnum, ShareClientEnum, ShareModelEnum, ShareEnum } from '@/core/enum';
	import type { Response } from '@/core/models';
	import { UserToken, shareUrl } from '@/core/consts'
	import { useCartStore, useLoginStore } from '@/core/store';
	import { handleShowToast, handleRouteNavigateTo, getShareUrl } from '@/core/utils';

	import GoodsDetail from '@/pages/components/goods-detail/index.vue';
	import GoodsDetailRecommend from '@/pages/components/goods-detail/components/goods-detail-recommend/goods-detail-recommend.vue';
	import GoodsDetailSkuPopup from '@/pages/components/goods-detail/components/goods-detail-sku/goods-detail-sku.vue';
	import GoodsDetailBottomTabbar from '@/pages/components/goods-detail/components/goods-detail-bottom-tabbar/goods-detail-bottom-tabbar.vue';
	import { useLoadingFn } from '@/core/hooks';

	interface QueryParams {
		id : number;
	}

	/** 登录store */
	const _useLoginStore = useLoginStore();

	const cartStore = useCartStore();

	const state = reactive<{
		goodsDetailData : any,
		swiperBanner : Array<string>;
		goodsDetailContent : string;
		showSku : boolean;
		shareUrl : string;
		id : number;
		showTip : boolean;
		spesDesc : string;
		timeData : {
			days : number,
			hours : number,
			minutes : number,
			seconds : number,
		}
	}>({
		goodsDetailData: {},
		swiperBanner: [],
		goodsDetailContent: "",
		showSku: false,
		shareUrl: "",
		id: 0,
		showTip: true,
		spesDesc: "",
		timeData: {
			days: 0,
			hours: 0,
			minutes: 0,
			seconds: 0,
		}
	});

	const loading = ref(false);
	const loadingPage = ref(true);
	const handleSeckillNow = useLoadingFn(onSeckillNow, loading);
	const handleGetGoodsDetail = useLoadingFn(getGoodsDetail, loadingPage);

	onLoad((query : QueryParams) => {
		state.id = Number(query.id);
		/** 获取商品详情 */
		handleGetGoodsDetail();
	});

	onPullDownRefresh(async () => {
		await handleGetGoodsDetail();
		uni.stopPullDownRefresh();
	});

	async function getGoodsDetail() {
		let data = {
			id: state.id,
			type: PaymentTypeEnum.seckill,
			needSku: true,
		}
		if (uni.getStorageSync(UserToken)) {
			data['token'] = uni.getStorageSync(UserToken);
		}
		const goodsDetail : Response<any> = await queryActivityDetial(data);

		/** 增加活动价格 */
		state.goodsDetailData = {
			...goodsDetail.data,
			activityPrice: goodsDetail.data?.product?.price,
		};

		/** 商品轮播图 */
		state.swiperBanner = goodsDetail?.data?.images?.split(',');
		/** 商品详情内容 */
		state.goodsDetailContent = goodsDetail?.data?.intro;
		/** 默认规格 */
		state.spesDesc = goodsDetail?.data?.product?.spesDesc;
		/** 如果用户登录，获取购物车数量 */
		if (uni.getStorageSync(UserToken)) {
			await getCartNum();
		}

		state.shareUrl = await getShareUrl({
			client: ShareClientEnum.wxMiNiProgram,
			url: shareUrl,
			type: ShareModelEnum.url,
			page: ShareEnum.seckill,
			params: {
				groupId: state.id
			}
		})
	}

	/** 获取购物车数量 */
	const getCartNum = async () => {
		const num : Response<number> = await queryCartNum();
		cartStore.setCartNum(num?.data || 0);
	}

	/** sku弹框显示隐藏 */
	const handleChangePopup = (show : boolean) => {
		state.showSku = show;
	}

	/** 时间倒计时 */
	const onChange = (e : any) => {
		state.timeData = e;
	}

	/** 立即购买，打开sku弹框 */
	const hanldeShowGoodSku = () => {
		_useLoginStore.checkLogin(() => {
			state.showSku = true;
		});
	}

	/** 立即秒杀 */
	async function onSeckillNow({ productId, nums } : any) {
		const addCart : Response<number> = await queryAddCart({
			ProductId: productId,
			Nums: nums,
			type: state.goodsDetailData.groupType,
			cartType: PaymentTypeEnum.seckill,
			objectId: state.id,
		});
		if (addCart.status) {
			handleRouteNavigateTo(`/pages/order/submit/submit?cartIds=${addCart.data}&orderType=${PaymentTypeEnum.seckill}&objectId=${state.id}`)
			/** 关闭sku弹框 */
			handleChangePopup(false);
		} else {
			handleShowToast(addCart.msg);
		}
	}

	/** 分享 */
	onShareAppMessage(() => {
		return {
			title: state.goodsDetailData.name,
			imageUrl: state.goodsDetailData.image,
			path: state.shareUrl
		}
	});
	onShareTimeline(() => {
		return {
			title: state.goodsDetailData.name,
			imageUrl: state.goodsDetailData.image,
			path: state.shareUrl
		}
	});
</script>
<style lang="scss" scoped>
	@import './detail.scss';
</style>